package solution;


class ListNode {
    int val;
    ListNode next;
    ListNode() {}
    ListNode(int val) { this.val = val; }
    ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}

class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode cur1 = l1;
        ListNode cur2 = l2;

        ListNode head = new ListNode();
        ListNode cur = head;

        boolean flag = false; //标识是否有进位，false 表示没有进位，true 表示有进位
        while (cur1 != null && cur2 != null) {
            int num = cur1.val + cur2.val;
            if (flag) {
                num++;
            }
            flag = false;
            if (num >= 10) {
                num %= 10;
                flag = true;
            }
            ListNode node = new ListNode(num);
            cur.next = node;
            cur = cur.next;
            cur1 = cur1.next;
            cur2 = cur2.next;
        }

        while (cur1 != null) {
            int num = cur1.val;
            if (flag) {
                num++;
            }
            flag = false;
            if (num >= 10) {
                num %= 10;
                flag = true;
            }
            ListNode node = new ListNode(num);
            cur.next = node;
            cur = cur.next;
            cur1 = cur1.next;
        }

        while (cur2 != null) {
            int num = cur2.val;
            if (flag) {
                num++;
            }
            flag = false;
            if (num >= 10) {
                num %= 10;
                flag = true;
            }
            ListNode node = new ListNode(num);
            cur.next = node;
            cur = cur.next;
            cur2 = cur2.next;
        }

        if (flag) {
            ListNode node = new ListNode(1);
            cur.next = node;
        }

        return head.next;
    }
}